package com.ict.txmsv2.schedule;

import com.ict.txmsv2.model.ClockIn;
import com.ict.txmsv2.model.SumTime;
import com.ict.txmsv2.model.User;
import com.ict.txmsv2.services.ClockInService;
import com.ict.txmsv2.services.SumtimeService;
import com.ict.txmsv2.services.UserService;
import com.ict.txmsv2.utils.DateUtils;
import com.ict.txmsv2.utils.SdfBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @author yoleen
 * @date 2020/12/21 21:04
 */

@Component
public class SumTimeSchedule {
    @Autowired
    SumtimeService sumtimeService;
    @Autowired
    UserService userService;

    @Scheduled(cron = "0 */12 * * * ?")
    public void updateSumTime(){
        String day = SdfBuilder.getSimpleDateFormat().format(new Date());
        List<User> users = userService.getUsersWithClockInByDay(day);
        for (User user : users) {
            if(sumtimeService.isExist(user.getId(),day)==0){
                sumtimeService.insertSumTime(user.getId(), day);
            }else {
                SumTime s = sumtimeService.getSumTime(user.getId(), day);
                long sum = 0;
                if(user.getClockIn()!=null){
                    for (int i = 1; i < user.getClockIn().size(); i+=2) {
                        sum += DateUtils.convertDateToLong(user.getClockIn().get(i).getDtt())
                                -DateUtils.convertDateToLong(user.getClockIn().get(i-1).getDtt());
                    }
                    s.setSumtime(Long.toString(sum));
                    sumtimeService.update(s);
                }
            }
        }
    }
}
